package com.ztc.ZtcTransport.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.service.AttachmentManager;
import com.aqgj.SysArea.bean.SysArea;
import com.aqgj.SysArea.service.SysAreaManager;
import com.aqgj.User.bean.User;
import com.aqgj.User.service.UserManager;
import com.aqgj.UserRole.bean.UserRole;
import com.aqgj.UserRole.service.UserRoleManager;
import com.aqgj.shiro.PasswordHash;
import com.aqgj.shiro.ShiroUser;
import com.aqgj.shiro.UsernamePasswordLoginTypeToken;
import com.aqgj.util.DateFarmatUtils;
import com.aqgj.util.ImageUtil;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.StringUtils;
import com.ztc.ZtcCar.bean.ZtcCar;
import com.ztc.ZtcCar.service.ZtcCarManager;
import com.ztc.ZtcDriver.bean.ZtcDriver;
import com.ztc.ZtcDriver.service.ZtcDriverManager;
import com.ztc.ZtcRefundRatio.bean.ZtcRefundRatioInfo;
import com.ztc.ZtcRefundRatio.service.ZtcRefundRatioInfoManager;
import com.ztc.ZtcTransportArea.bean.ZtcTransportArea;
import com.ztc.ZtcTransportArea.service.ZtcTransportAreaManager;
import com.ztc.ZtcTransportDefaultPercentage.bean.ZtcTransportDefaultPercentage;
import com.ztc.ZtcTransportDefaultPercentage.service.ZtcTransportDefaultPercentageManager;
import com.ztc.ZtcTransportPercentageScale.bean.ZtcTransportPercentageScale;
import com.ztc.ZtcTransportPercentageScale.service.ZtcTransportPercentageScaleManager;
import com.ztc.ZtcWallet.bean.ZtcWallet;
import com.ztc.ZtcWallet.service.ZtcWalletManager;
import com.ztc.util.SingleSendSms;
import com.ztc.util.ZtcCompanyScaleUtil;
import com.ztc.util.sms.SMSUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("ztc_transport_action")
public class ZtcTransportAction {

    @Autowired
    private ZtcTransportManager ztcTransportManager;
    @Autowired
    private AttachmentManager attachmentManager;
    @Autowired
    private UserManager userManager;
    @Autowired
    private ZtcTransportAreaManager ztcTransportAreaManager;
    @Autowired
    private SysAreaManager sysAreaManager;
    @Autowired
    private ZtcCarManager ztcCarManager;
    @Autowired
    private ZtcDriverManager ztcDriverManager;
    @Autowired
    private PasswordHash passwordHash;
    @Autowired
    private UserRoleManager userRoleManager;
    @Autowired
    private ZtcRefundRatioInfoManager ztcRefundRatioInfoManager;
    @Autowired
    private ZtcTransportPercentageScaleManager ztcTransportPercentageScaleManager;
    @Autowired
    ZtcTransportDefaultPercentageManager ztcTransportDefaultPercentageManager;
    @Autowired
    ZtcWalletManager ztcWalletManager;

    private static final Logger logger= LogManager.getLogger(ZtcTransportAction.class);

    /**
     * 运营公司注册.
     *
     * @param ztcTransport 公司对象
     * @param files        上传的附件
     * @param request
     * @param business_img 营业执照workItem
     * @param trade_img    行业许可证workItem
     * @return
     */
    @RequestMapping(value = "sign", method = RequestMethod.POST)
    public String sign(ZtcTransport ztcTransport, @RequestParam("files") MultipartFile[] files, HttpServletRequest request, String business_img, String trade_img, String vCode, HttpSession session, User user, Model model) {
        ObjectMapper objectMapper = new ObjectMapper();
        String msg = null;
        try {
            if (ztcTransport.getSignTel() == null || "".equals(ztcTransport.getSignTel())) {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("请输入电话号码!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            if (vCode == null || "".equals(vCode)) {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("请输入验证码!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
            if (map != null) {
                if (!map.get("smscode").equals(vCode)) {
                    msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!"));
                    model.addAttribute("msg", msg);
                    return "error";
                }
                if (!map.get("mobile").equals(ztcTransport.getSignTel())) {
                    msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("输入的手机号码异常，请重新输入!"));
                    model.addAttribute("msg", msg);
                    return "error";
                }
            } else {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            if (user.getPassword() == null || "".equals(user.getPassword())) {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("请设置登录密码!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            ZtcTransport test = ztcTransportManager.findUniqueBy("fullName", ztcTransport.getFullName());
            if (test != null) {
                if(test.getStatus()==2&&test.getSignTel().equals(ztcTransport.getSignTel())){//审核未通过且手机号通过验证
                    List<Attachment> list=attachmentManager.getAttachmentByBusinessId(test.getId());
                    if(list.size()>0){
                        for (Attachment a:list) {
                            attachmentManager.deleteAttachment(a);//删除证件
                        }
                    }
                    User u=userManager.findUniqueBy("account",test.getSignTel());
                    userManager.removeById(u.getId());//删除登录用户
                    ztcTransportManager.delZtcTransport(test.getId());//公司删除
                }
            }
            User user1 = userManager.findUniqueBy("account", ztcTransport.getSignTel());
            if (user1 != null) {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            user.setAccount(ztcTransport.getSignTel());
            user.setTelPhone(ztcTransport.getSignTel());
            user.setStatus("1");
            user.setUserType("1");
            String slat=StringUtils.getUUId();
            String pwd = passwordHash.toHex(user.getPassword(), slat);
            user.setSalt(slat);
            user.setPassword(pwd);
            user.setCurrTime(new Date());
            user.setRemark("公司注册用户");
            String uid = userManager.save(user);
            if (uid == null) {
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!"));
                model.addAttribute("msg", msg);
                return "error";
            }
            SysArea sysArea = sysAreaManager.findUniqueBy("code", ztcTransport.getAreaCode());
            HashMap<String, Object> transportResult = ztcTransportManager.saveZtcTransport(ztcTransport, 3, 1, ztcTransportAreaManager.getZtaByAreaId(sysArea.getId()).getId());//3运营公司
            if (transportResult.get("success").equals(true)) {
                if (business_img == null || "".equals(business_img)) {
                    userManager.removeById(uid);
                    ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                    msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("请上传公司营业执照，以便审核!"));
                    model.addAttribute("msg", msg);
                    return "error";
                }
                if (trade_img == null || "".equals(trade_img)) {
                    userManager.removeById(uid);
                    ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                    msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("请上传行业许可证，以便审核!"));
                    model.addAttribute("msg", msg);
                    return "error";
                }
                if (files != null && files.length >= 2) {
                    for (int i = 0; i < files.length; i++) {
                        MultipartFile file = files[i];
                        Attachment attachment = new Attachment();
                        attachment.setFileType(file.getContentType());
                        attachment.setFileSize(String.valueOf(file.getSize()));
                        attachment.setFileName(file.getOriginalFilename());
                        attachment.setUploadTime(new Date());
                        attachment.setUploaderName("公司注册");
                        attachment.setBusinessId(String.valueOf(transportResult.get("data")));
                        if (file.getOriginalFilename().equals(business_img)) {
                            attachment.setWorkItem("business_img");
                        }
                        if (file.getOriginalFilename().equals(trade_img)) {
                            attachment.setWorkItem("trade_img");
                        }
                        InputStream rfile = ImageUtil.markImageByText("An168", file.getInputStream(), -45);
                        byte[] data = new byte[rfile.available()];
                        rfile.read(data);
                        attachment.setFileBody(data);
                        String id = attachmentManager.saveAttachment(attachment, request, true);
                        attachment.setFilePath(id);
                        attachmentManager.save(attachment);
                    }
                    User user2 = userManager.get(uid);
                    user2.setTransportId(String.valueOf(transportResult.get("data")));
                    userManager.save(user2);
                    msg = objectMapper.writeValueAsString(JsonWrapper.successWrapper("注册成功，请等待审核!"));
                    model.addAttribute("msg", msg);
                    return "error";
                } else {
                    userManager.removeById(uid);
                    ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                    msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg("注册需上传证件信息，以便审核!"));
                    model.addAttribute("msg", msg);
                    return "error";
                }
            } else {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                msg = objectMapper.writeValueAsString(JsonWrapper.failureWrapperMsg(String.valueOf(transportResult.get("msg"))));
                model.addAttribute("msg", msg);
                return "error";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 获取短信验证码/手机号登录.
     *
     * @param mobile   手机号码
     * @param session
     * @param vCode    手机验证码
     * @return
     */
    @RequestMapping("sendSms")
    @ResponseBody
    public HashMap<String, Object> sendSms(String mobile, HttpSession session,String vCode,HttpServletRequest request) {
         HashMap<String, String> map1 = (HashMap<String, String>) session.getAttribute("smsCode");
        if (map1 != null) {
            System.out.println(map1.get("smscode").toString());
        }
        if (vCode != null) { //手机验证码登录
            User user = userManager.findUserByAccount(mobile);
            Integer cType=6;
            if (user != null) {
                ZtcTransport ztcTransport = ztcTransportManager.get(user.getTransportId());
                if(ztcTransport!=null) {
                    cType=ztcTransport.getType();
                    if (ztcTransport.getStatus() == 1) {
                        return JsonWrapper.failureWrapperMsg("请等待审核!");
                    }
                    if (ztcTransport.getStatus() == 2) {
                        return JsonWrapper.failureWrapperMsg("未通过审核," + ztcTransport.getExamineRemark());
                    }
                }else{
                    return JsonWrapper.failureWrapperMsg("该账户不允许登录！");
                }
            }else{
                return JsonWrapper.failureWrapperMsg("账户不存在！");
            }
            if (map1 != null && map1.get("smscode").equals(vCode)) {
                Subject currentUser = SecurityUtils.getSubject();
                UsernamePasswordLoginTypeToken token = new UsernamePasswordLoginTypeToken(user.getAccount(),"123456",true);
                try {
                    SecurityUtils.getSubject().login(token);
                    currentUser.getSession().setAttribute("userInfo",user);
                } catch (Exception e) {
                    return JsonWrapper.failureWrapperMsg("请尝试重新登录！");
                }

                // 读取用户的url和角色
                Map<String, Set<String>> resourceMap = userRoleManager.selectResourceMapByUserId(user.getId());
                Set<String> urls = resourceMap.get("urls");
                Set<String> roles = resourceMap.get("roles");
                ShiroUser shiroUser = new ShiroUser(user.getId(), user.getAccount(), user.getName(),cType, urls);
                shiroUser.setRoles(roles);
                return JsonWrapper.successWrapper(shiroUser);
            } else {
                return JsonWrapper.failureWrapperMsg("登陆失败,验证码错误!");
            }
        } else {
            String smscode = String.valueOf(SMSUtil.getRanNum(1000, 9999));
            Map<String, String> code = new HashMap<>();
            code.put("code",smscode);
            code.put("product","安旗An168");
            boolean isTrue = SingleSendSms.SendSms(code, 1, mobile);
            if (isTrue == false) {
                return JsonWrapper.failureWrapperMsg("发送失败！");
            }
            Map<String, String> map = new HashMap<>();
            map.put("smscode", smscode);
            map.put("mobile", mobile);
            session.setAttribute("smsCode", map);
            HashMap<String, String> map2 = (HashMap<String, String>) session.getAttribute("smsCode");
            if (map2 != null) {
                System.out.println(map2.get("smscode").toString());
            }
        }
        return JsonWrapper.successWrapper("发送成功！");
    }

    /**
     * 后台添加省管理，地区管理公司.
     *
     * @param ztcTransport 公司
     * @param level    公司级别（0总公司，1省管理公司，2地级市公司，3运营公司，4车方公司）
     * @return
     */
    @RequestMapping("saveCompany")
    @ResponseBody
    @Transactional
    public HashMap<String, Object> saveCompany(ZtcTransport ztcTransport, User user, Integer level, String areaId) {
        if (level != 1 && level != 2) {
            return JsonWrapper.failureWrapperMsg("公司类型参数指向性错误！");
        }
        if (ztcTransport.getAreaCode() == null || areaId == null) {
            return JsonWrapper.failureWrapperMsg("区域参数空指针错误！");
        }
        if(ztcTransport.getSignTel()!=null){
            User user1=userManager.findUniqueBy("account",ztcTransport.getSignTel());
            if(user1!=null){
                return JsonWrapper.failureWrapperMsg("手机账户已存在！");
            }
        }else{
            return JsonWrapper.failureWrapperMsg("手机号码不能为空！");
        }
        SysArea area = sysAreaManager.findUniqueBy("code", ztcTransport.getAreaCode());
        JSONArray jsonArray = JSON.parseArray(areaId);
        //判断所选管理区域是否存在已被管理关系
        if (jsonArray.size() > 0) {
            for (Object ce : jsonArray) {
                ZtcTransportArea ztcTransportArea = ztcTransportAreaManager.findUniqueBy("areaId", ce);
                if (ztcTransportArea != null) {
                    return JsonWrapper.failureWrapperMsg("所选区域‘" + sysAreaManager.get(ce.toString()).getName() + "’已存在管理关系！");
                }
            }
        }
        String pid = "";
        if (level == 2) {
            String id = "";
            if (area.getType() == 1) {//直辖市
                id = sysAreaManager.get(area.getPid()).getPid();//三级行政区划的省级区划id
            } else {
                id = sysAreaManager.get(sysAreaManager.findUniqueBy("code", ztcTransport.getAreaCode()).getPid()).getPid();//二级行政区划的省级区划id
            }
            ZtcTransportArea ztcTransportArea2 = ztcTransportAreaManager.findUniqueBy("areaId", id);//省公司关系
            if (ztcTransportArea2 == null) {
                return JsonWrapper.failureWrapperMsg("所选区域不存在省级管理公司！");
            } else {
                pid = ztcTransportArea2.getTransportId();
            }
        } else {
            pid = ztcTransportManager.findBy("type", 0).get(0).getId();
        }
        HashMap<String, Object> transportResult = ztcTransportManager.saveZtcTransport(ztcTransport, level, 3, pid);
        if (transportResult.get("success").equals(true)) {
            user.setAccount(ztcTransport.getSignTel());
            user.setTelPhone(ztcTransport.getSignTel());
            user.setStatus("1");
            String slat = StringUtils.getUUId();
            String pwd = passwordHash.toHex(user.getPassword(), slat);
            user.setSalt(slat);
            user.setPassword(pwd);
            user.setCurrTime(new Date());
            user.setUserType("1");
            user.setRemark("管理公司用户");
            user.setTransportId(String.valueOf(transportResult.get("data")));
            String uid= userManager.save(user);
            if(uid!=null){
                //设置角色
                if(level==1){
                    UserRole userRole=new UserRole();
                    userRole.setRoleId("402893815fec9fa8015feceee7e30058");
                    userRole.setUserId(uid);
                    userRoleManager.save(userRole);
                }else{
                    UserRole userRole=new UserRole();
                    userRole.setRoleId("402893815fec9fa8015fecef3ea90059");
                    userRole.setUserId(uid);
                    userRoleManager.save(userRole);
                }
            }
            if(jsonArray.size()>0){
                for (Object ce : jsonArray) {
                  ZtcTransportArea  ztcTransportArea = new ZtcTransportArea();
                    ztcTransportArea.setTransportId(String.valueOf(transportResult.get("data")));
                    ztcTransportArea.setAreaId(ce.toString());
                    ztcTransportAreaManager.save(ztcTransportArea);
                }
            }

            //系统默认提成比例方案
            List<ZtcTransportDefaultPercentage> ztcTransportDefaultPercentageList=ztcTransportDefaultPercentageManager.getAll();
            ZtcTransportDefaultPercentage ztcTransportDefaultPercentage=ztcTransportDefaultPercentageList.get(0);

            //设置公司提成收益比例
            ZtcTransportPercentageScale ztcTransportPercentageScale = ZtcCompanyScaleUtil.setCompanyPercentageScale(ztcTransportDefaultPercentage, ztcTransport.getType(),String.valueOf(transportResult.get("data")));
            ztcTransportPercentageScaleManager.save(ztcTransportPercentageScale);

            //初始化公司钱包
            ZtcWallet ztcWallet = new ZtcWallet();
            ztcWallet.setMoney(new BigDecimal(0));
            ztcWallet.setFkUserId(String.valueOf(transportResult.get("data")));
            ztcWallet.setBusinessType(2);

            ztcWalletManager.save(ztcWallet);

            return JsonWrapper.successWrapper("添加注册成功！");
        }
        return JsonWrapper.failureWrapperMsg(String.valueOf(transportResult.get("msg")));
    }

    /**
     * 车方注册.
     *
     * @param ztcTransport   公司信息
     * @param files          上传文件
     * @param request
     * @param carSide_img    车身斜照workItem
     * @param driver_lic_img 行驶证workItem
     * @param Operation_img  运营证workItem
     * @param ride_img       乘坐险workItem
     * @param head_img       司机头像workItem
     * @param driver_img     驾驶证workItem
     * @param cert_img       资格证workItem
     * @param work_img       上岗证workItem
     * @param vCode          手机验证码
     * @param session
     * @param user           车方用户信息
     * @param ztcCar         车辆信息
     * @param ztcDriver      车辆信息
     * @param model
     * @return 注册结果返回信息
     */
    @RequestMapping(value = "signCut", method = RequestMethod.POST)
    public String signCut(ZtcTransport ztcTransport, @RequestParam("files") MultipartFile[] files, HttpServletRequest request, String carSide_img, String driver_lic_img, String Operation_img, String ride_img, String head_img, String driver_img, String cert_img, String work_img,
                          ZtcCar ztcCar, ZtcDriver ztcDriver, String vCode, HttpSession session, User user, Model model,String pid) {

        if (ztcTransport.getSignTel() == null || "".equals(ztcTransport.getSignTel())) {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请输入电话号码!")));
            return "error";
        }
        if (vCode == null || "".equals(vCode)) {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请输入验证码!")));
            return "error";
        }
        //手机验证码
        HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
        if (map != null) {
            if (!map.get("smscode").equals(vCode)) {
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!")));
                return "error";
            }
            if (!map.get("mobile").equals(ztcTransport.getSignTel())) {
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("输入的手机号码异常，请重新输入!")));
                return "error";
            }
        } else {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!")));
            return "error";
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请设置登录密码!")));
            return "error";
        }
        ZtcTransport test = ztcTransportManager.findUniqueBy("fullName", ztcTransport.getFullName());
        if (test != null) {
            if(test.getStatus()==2&&test.getSignTel().equals(ztcTransport.getSignTel())){//审核未通过且手机号通过验证
                List<Attachment> list=attachmentManager.getAttachmentByBusinessId(test.getId());
                if(list.size()>0){
                    for (Attachment a:list) {
                        attachmentManager.deleteAttachment(a);//删除证件
                    }
                }
                User u=userManager.findUniqueBy("account",test.getSignTel());
                userManager.removeById(u.getId());//删除注册登录用户
                List<ZtcDriver> ztcDrivers=ztcDriverManager.findBy("transportId",test.getId());
                ztcDriverManager.removeById(ztcDrivers.get(0).getId());//删除注册司机
                List<ZtcCar> ztcCars=ztcCarManager.findBy("transportId",test.getId());
                ztcCarManager.removeById(ztcCars.get(0).getId());//删除注册车辆
                ztcTransportManager.delZtcTransport(test.getId());//公司删除
            }
        }
        User user1 = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (user1 != null) {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!")));
            return "error";
        }
        user.setAccount(ztcTransport.getSignTel());
        user.setTelPhone(ztcTransport.getSignTel());
        user.setStatus("1");
        String slat=StringUtils.getUUId();
        String pwd = passwordHash.toHex(user.getPassword(), slat);
        user.setSalt(slat);
        user.setPassword(pwd);
        user.setUserType("1");
        user.setCurrTime(new Date());
        user.setRemark("车方注册用户");
        String uid = userManager.save(user);
        if (uid == null) {
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!")));
            return "error";
        }
        List<ZtcTransport> ztcTransports = ztcTransportManager.findBy("areaCode", ztcTransport.getAreaCode(), "type", 3);
        if (ztcTransports.size() <= 0) {
            userManager.removeById(uid);
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("该区域没有运营公司，无法注册！")));
            return "error";
        }
        if (pid==null||"".equals(pid)) {
            userManager.removeById(uid);
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("该区域没有运营公司，无法注册！")));
            return "error";
        }
        //保存车方公司信息
        HashMap<String, Object> transportResult = ztcTransportManager.saveZtcTransport(ztcTransport, 4, 1, pid);//4车方公司
        if (transportResult.get("success").equals(true)) {
            if (carSide_img == null || "".equals(carSide_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传车身照片，以便审核!")));
                return "error";
            }
            if (driver_lic_img == null || "".equals(driver_lic_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传行驶证照片，以便审核!")));
                return "error";
            }
            if (Operation_img == null || "".equals(Operation_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传运营证照片，以便审核!")));
                return "error";
            }
            if (ride_img == null || "".equals(ride_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传乘坐险照片，以便审核!")));
                return "error";
            }
            if (head_img == null || "".equals(head_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传司机正照，以便审核!")));
                return "error";
            }
            if (driver_img == null || "".equals(driver_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传驾驶证照片，以便审核!")));
                return "error";
            }
            if (cert_img == null || "".equals(cert_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传资格证照片，以便审核!")));
                return "error";
            }
            if (work_img == null || "".equals(work_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("请上传上岗证照片，以便审核!")));
                return "error";
            }
            ztcCar.setTransportId(String.valueOf(transportResult.get("data")));
            ztcCar.setStatus(5);
            ztcDriver.setTransportId(String.valueOf(transportResult.get("data")));
            ztcDriver.setStatus("5");
            ztcDriver.setSignTime(new Date());
            String carId = ztcCarManager.save(ztcCar);
            String did = ztcDriverManager.save(ztcDriver);
            if (files != null && files.length >= 8) {
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    Attachment attachment = new Attachment();
                    attachment.setFileType(file.getContentType());
                    attachment.setFileSize(String.valueOf(file.getSize()));
                    attachment.setFileName(file.getOriginalFilename());
                    attachment.setUploadTime(new Date());
                    attachment.setUploaderName("车方注册");
                    if (file.getOriginalFilename().equals(carSide_img)) {
                        attachment.setWorkItem("carSide_img");
                        attachment.setBusinessId(carId);
                    }
                    if (file.getOriginalFilename().equals(driver_lic_img)) {
                        attachment.setWorkItem("driver_lic_img");
                        attachment.setBusinessId(carId);
                    }
                    if (file.getOriginalFilename().equals(Operation_img)) {
                        attachment.setWorkItem("Operation_img");
                        attachment.setBusinessId(carId);
                    }
                    if (file.getOriginalFilename().equals(ride_img)) {
                        attachment.setWorkItem("ride_img");
                        attachment.setBusinessId(carId);
                    }
                    if (file.getOriginalFilename().equals(head_img)) {
                        attachment.setWorkItem("head_img");
                        attachment.setBusinessId(did);
                    }
                    if (file.getOriginalFilename().equals(driver_img)) {
                        attachment.setWorkItem("driver_img");
                        attachment.setBusinessId(did);
                    }
                    if (file.getOriginalFilename().equals(cert_img)) {
                        attachment.setWorkItem("cert_img");
                        attachment.setBusinessId(did);
                    }
                    if (file.getOriginalFilename().equals(work_img)) {
                        attachment.setWorkItem("work_img");
                        attachment.setBusinessId(did);
                    }

                    try {
                        InputStream rfile = ImageUtil.markImageByText("An168", file.getInputStream(), -45);
                        byte[] data = new byte[rfile.available()];
                        rfile.read(data);
                        attachment.setFileBody(data);
                    } catch (IOException e) {
                        ztcCarManager.removeById(carId);
                        userManager.removeById(uid);
                        ztcDriverManager.removeById(did);
                        ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                        model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg(e.getMessage().toString())));
                        return "error";
                    }
                    String id = attachmentManager.saveAttachment(attachment, request, true);
                    attachment.setFilePath(id);
                    attachmentManager.save(attachment);
                }
                User user2 = userManager.get(uid);
                user2.setTransportId(String.valueOf(transportResult.get("data")));
                userManager.save(user2);
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.successWrapper("注册成功，请等待审核!")));
                return "error";
            } else {
                ztcDriverManager.removeById(did);
                ztcCarManager.removeById(carId);
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg("注册需上传证件信息，以便审核!")));
                return "error";
            }
        } else {
            userManager.removeById(uid);
            ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
            model.addAttribute("msg", JSONObject.toJSONString(JsonWrapper.failureWrapperMsg(String.valueOf(transportResult.get("msg")))));
            return "error";
        }
    }

    /**
     * 车方注册时根据选择区域代码获取该区域是否存在运营公司.
     *
     * @param areaCode 区域代码
     * @return Json, 查询成功返回公司，不存在返回false
     */
    @RequestMapping("getAreaCompanyByAreaCode")
    @ResponseBody
    public HashMap<String, Object> getAreaCompanyByAreaCode(String areaCode) {
        List<ZtcTransport> ztcTransports = ztcTransportManager.findBy("areaCode", areaCode, "type", 3);
        List<HashMap<String,Object>> mapList=new ArrayList<>();
        if(ztcTransports.size()>0){
            for (ZtcTransport z:ztcTransports) {
                if(z.getStatus()==3){
                    HashMap<String,Object> map=new HashMap<>();
                    map.put("id",z.getId());
                    map.put("fullName",z.getFullName());
                    mapList.add(map);
                }
            }
            if(mapList.size()>0){
                return JsonWrapper.successWrapper(mapList);
            }else{
                return JsonWrapper.failureWrapperMsg("该区域没有运营公司，无法注册！");
            }
        }else{
            return JsonWrapper.failureWrapperMsg("该区域没有运营公司，无法注册！");
        }
    }


    /**
     * 根据当前公司获取旗下管理的所有子公司.
     * @param pageSize  每页大小
     * @param pageNumber  页码
     * @param type    指定类型（3运营，4车方）
     * @return   所有满足条件的公司信息
     */
    @RequestMapping("getAllCompany")
    @ResponseBody
    public HashMap<String, Object> getAllCompany(HttpSession session,Integer pageSize,Integer pageNumber,Integer type,String search,Integer status) {
        User currUser = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport = ztcTransportManager.get(currUser.getTransportId());
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("数据异常错误，请稍后重试！");
        }
        if(type==null){
            return JsonWrapper.failureWrapperMsg("参数错误！");
        }
        if(pageSize==null||pageNumber==null){
            return JsonWrapper.failureWrapperMsg("分页参数错误！");
        }
        return ztcTransportManager.getAllCompany(ztcTransport.getId(),pageSize,pageNumber,type,search,status,ztcTransport.getType());
    }

    /**
     * 根据公司id审核该公司（通过审核）.
     *
     * @param companyId 待审核公司id
     * @param status    通过状态(1注册未审核，2未通过审核，3正常，4冻结)
     * @param remark    审核意见
     * @param endTime   有效期结束时间
     * @return
     */
    @RequestMapping("reviewedCompany")
    @ResponseBody
    @Transactional
    public HashMap<String, Object> reviewedCompany(String companyId, Integer status, String remark, String endTime, HttpSession session) {
        if (status == null) {
            return JsonWrapper.failureWrapperMsg("参数错误，请稍后重试！");
        }
        if (status != 3) {
            return JsonWrapper.failureWrapperMsg("状态参数指向性错误！");
        }
        ZtcTransport ztcTransport = ztcTransportManager.get(companyId);
        User currUser = (User) session.getAttribute("userInfo");
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        if (!currUser.getTransportId().equals(ztcTransport.getParentId())) {
            return JsonWrapper.failureWrapperMsg("非直属上级公司，无权限进行该操作！");
        }
        ZtcTransport ztcTransport1 = ztcTransportManager.get(currUser.getTransportId());
        if (ztcTransport1 == null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试!");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus() == 4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        if (ztcTransport.getType() == 4 && ztcTransport1.getType() != 3) {
            return JsonWrapper.failureWrapperMsg("非运营公司无权限进行该操作！");
        }
        if (endTime == null||"".equals(endTime)) {
            return JsonWrapper.failureWrapperMsg("证件到期日期未选择！");
        }
        if (ztcTransport.getStatus() != 1 && ztcTransport.getStatus() != 5) {
            return JsonWrapper.failureWrapperMsg("该公司已经审核过！");
        }
        //注册待审核
        if (ztcTransport.getStatus() == 1) {
            //注册用户
            User user = userManager.findUserByAccount(ztcTransport.getSignTel());
            //系统默认提成比例方案
            List<ZtcTransportDefaultPercentage> ztcTransportDefaultPercentageList = ztcTransportDefaultPercentageManager.getAll();
            ZtcTransportDefaultPercentage ztcTransportDefaultPercentage = ztcTransportDefaultPercentageList.get(0);
            if (ztcTransport.getType() == 3) {
                ZtcRefundRatioInfo ztcRefundRatioInfo1 = ztcRefundRatioInfoManager.findUniqueBy("createTransportId", ztcTransport.getId());
                if (ztcRefundRatioInfo1 == null) {
                    //退票扣费比例
                    HashMap<String, Object> resultMap = ZtcCompanyScaleUtil.setOperation(ztcTransport.getId());
                    ZtcRefundRatioInfo ztcRefundRatioInfo = (ZtcRefundRatioInfo) resultMap.get("ztcRefundRatioInfo");
                    ztcRefundRatioInfoManager.saveInfo(ztcRefundRatioInfo, resultMap.get("ztcRefundRatio").toString());
                    logger.info("============运营公司退票扣费比例初始化==============");
                }
                if (ztcTransport.getDistributorRebateProportion() == null && ztcTransport.getUserRebateProportion() == null) {
                    //设置分销商返佣比例及普通用户返佣比例
                    ztcTransport = ZtcCompanyScaleUtil.setOperationCompany(ztcTransport, ztcTransportDefaultPercentage.getDealerUserLevelScale(), ztcTransportDefaultPercentage.getCommonUserLevelScale());
                    logger.info("============设置分销商返佣比例及普通用户返佣比例==============");
                }
                if (user != null) {
                    //设置角色
                    UserRole userRole = new UserRole();
                    userRole.setRoleId("402880f25fe7b388015fe7cc729e0047");
                    userRole.setUserId(user.getId());
                    userRoleManager.save(userRole);
                }
            } else {
                if (user != null) {
                    //设置角色
                    UserRole userRole = new UserRole();
                    userRole.setRoleId("402880f25fe7b388015fe7c01e140036");
                    userRole.setUserId(user.getId());
                    userRoleManager.save(userRole);
                }
            }
            ZtcTransportPercentageScale ztcTransportPercentageScale1 = ztcTransportPercentageScaleManager.findUniqueBy("transportId", ztcTransport.getId());
            if (ztcTransportPercentageScale1 == null) {
                //设置公司提成收益比例
                ZtcTransportPercentageScale ztcTransportPercentageScale = ZtcCompanyScaleUtil.setCompanyPercentageScale(ztcTransportDefaultPercentage, ztcTransport.getType(), ztcTransport.getId());
                ztcTransportPercentageScaleManager.save(ztcTransportPercentageScale);
                logger.info("============公司提成收益比例初始化==============");
            }
            ZtcWallet ztcWallet1 = ztcWalletManager.findUserWallet(ztcTransport.getId());
            if (ztcWallet1 == null) {
                //初始化公司钱包
                ZtcWallet ztcWallet = new ZtcWallet();
                ztcWallet.setMoney(BigDecimal.ZERO);
                ztcWallet.setTmoney(BigDecimal.ZERO);
                ztcWallet.setFkUserId(ztcTransport.getId());
                ztcWallet.setBusinessType(2);
                logger.info("============公司钱包初始化==============");
                ztcWalletManager.save(ztcWallet);
            }
        }else{//再次审核
            List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
            if (list.size() > 0) {
                for (Attachment a : list) {
                    if ("oBusiness_img".equals(a.getWorkItem())) {
                        //如果通过审核,需要删除原照片
                        attachmentManager.deleteAttachment(a);
                        continue;
                    }
                    if ("oTrade_img".equals(a.getWorkItem())) {
                        attachmentManager.deleteAttachment(a);
                    }
                }
            }
        }
        return ztcTransportManager.reviewedCompany(ztcTransport, status, remark, endTime, currUser);
    }

    /**
     * 根据公司id审核该公司（不通过审核）.
     *
     * @param companyId 待审核公司id
     * @param status    通过状态(1注册未审核，2未通过审核，3已通过审核)
     * @param remark    审核意见
     * @return
     */
    @RequestMapping("unReviewedCompany")
    @ResponseBody
    public HashMap<String, Object> unReviewedCompany(String companyId, Integer status, String remark,HttpSession session) {
        ZtcTransport ztcTransport = ztcTransportManager.get(companyId);
        User currUser = (User) session.getAttribute("userInfo");
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        if(!currUser.getTransportId().equals(ztcTransport.getParentId())){
            return JsonWrapper.failureWrapperMsg("非直属上级公司，无权限进行该操作！");
        }
        ZtcTransport ztcTransport1 = ztcTransportManager.get(currUser.getTransportId());
        if (ztcTransport1==null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试!");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        if(ztcTransport.getType()==4&&ztcTransport1.getType()!=3){
            return JsonWrapper.failureWrapperMsg("非运营公司无权限进行该操作！");
        }
        if (status !=2 && status!=6) {
            return JsonWrapper.failureWrapperMsg("状态参数指向性错误！");
        }
        if (ztcTransport.getStatus()!=1 && ztcTransport.getStatus()!=5) {
            return JsonWrapper.failureWrapperMsg("该公司信息已审核过！");
        }
        ztcTransport.setStatus(status);
        ztcTransport.setExamineRemark(remark);
        ztcTransport.setExamineTime(new Date());
        ztcTransport.setExamineUserId(currUser.getId());
        ztcTransport.setExamineUsername(currUser.getAccount());
        ztcTransportManager.save(ztcTransport);
        return JsonWrapper.successWrapper("操作成功！");
    }

    /**
     * 冻结或解冻公司.
     *
     * @param id     公司id
     * @param status 状态(3解冻，4冻结)
     * @return
     */
    @RequestMapping("setEnabled")
    @ResponseBody
    public HashMap<String, Object> setEnabled(HttpSession session,String id, Integer status) {
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(user.getTransportId());
        if (ztcTransport1==null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试!");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        ZtcTransport ztcTransport = ztcTransportManager.get(id);
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        //未通过审核的公司无法冻结操作
        if (ztcTransport.getStatus()==2) {
            return JsonWrapper.failureWrapperMsg("不被允许的操作！");
        }
        return ztcTransportManager.setTransportStatus(status,ztcTransport,user);
    }

    /**
     * 根据公司id获取公司详情（审核使用）.
     *
     * @param companyId 待审核公司id
     * @return
     */
    @RequestMapping("getDetail")
    @ResponseBody
    public HashMap<String, Object> getDetail(String companyId) {
        ZtcTransport ztcTransport = ztcTransportManager.get(companyId);
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        User user = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (user == null) {
            return JsonWrapper.failureWrapperMsg("获取用户信息失败,不存在该注册用户！");
        }
        List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("ztcName", ztcTransport.getFullName());
        map.put("signTel", ztcTransport.getSignTel());
        map.put("address", ztcTransport.getAddress());
        map.put("time", DateFarmatUtils.format(ztcTransport.getSignTime()));
        map.put("cid", ztcTransport.getId());
        map.put("account", user.getAccount());
        map.put("status", ztcTransport.getStatus());
        map.put("location",sysAreaManager.findUniqueBy("code",ztcTransport.getAreaCode()).getFullName());
        map.put("email", ztcTransport.getEmail());
        map.put("telPhone", user.getTelPhone());
        map.put("uName", user.getName());
        if (ztcTransport.getType()==3||ztcTransport.getType()==5) {//运营公司
            map.put("type", "运营公司");
            if (list.size() > 0) {
                for (Attachment a : list) {
                    if ("business_img".equals(a.getWorkItem())) {
                        map.put("bFilePath", a.getFilePath());
                        map.put("bFileName", a.getFileName());
                        continue;
                    }
                    if ("trade_img".equals(a.getWorkItem())) {
                        map.put("tFilePath", a.getFilePath());
                        map.put("tFileName", a.getFileName());
                        continue;
                    }
                    if ("oBusiness_img".equals(a.getWorkItem())) {
                        map.put("obFilePath", a.getFilePath());
                        map.put("obFileName", a.getFileName());
                        continue;
                    }
                    if ("oTrade_img".equals(a.getWorkItem())) {
                        map.put("otFilePath", a.getFilePath());
                        map.put("otFileName", a.getFileName());
                    }
                }
            }
        }
        if (ztcTransport.getType()==4) {//车方公司
            List<ZtcDriver> ztcDriverList = ztcDriverManager.getZtcDriverByTransportId(ztcTransport.getId());
            List<ZtcCar> carList = ztcCarManager.findBy("transportId",ztcTransport.getId(),"status",5);
            if (ztcDriverList.size() <= 0) {
                return JsonWrapper.failureWrapperMsg("获取注册司机信息失败！");
            }
            if (carList.size() <= 0) {
                return JsonWrapper.failureWrapperMsg("获取注册汽车信息失败！");
            }
            List<Attachment> cars = attachmentManager.getAttachmentByBusinessId(carList.get(0).getId());
            List<Attachment> drivers = attachmentManager.getAttachmentByBusinessId(ztcDriverList.get(0).getId());
            map.put("type", "车方公司");
            map.put("driverName", ztcDriverList.get(0).getdName());
            map.put("dTel", ztcDriverList.get(0).getPhone());
            map.put("dCard", ztcDriverList.get(0).getDriverCard());
            map.put("brand", carList.get(0).getBrand());
            map.put("carNumber", carList.get(0).getCarNumber());
            map.put("color", carList.get(0).getColor());
            map.put("origin", carList.get(0).getOrigin());
            map.put("property", carList.get(0).getProperty());
            map.put("carSeat", carList.get(0).getSeatNum());
            map.put("carType", carList.get(0).getCarType());
            if (cars.size() > 0) {
                for (Attachment a : cars) {
                    if ("carSide_img".equals(a.getWorkItem())) {
                        map.put("carFilePath", a.getFilePath());
                        map.put("carFileName", a.getFileName());
                        continue;
                    }
                    if ("driver_lic_img".equals(a.getWorkItem())) {
                        map.put("lFilePath", a.getFilePath());
                        map.put("lFileName", a.getFileName());
                        continue;
                    }
                    if ("Operation_img".equals(a.getWorkItem())) {
                        map.put("oFilePath", a.getFilePath());
                        map.put("oFileName", a.getFileName());
                        continue;
                    }
                    if ("ride_img".equals(a.getWorkItem())) {
                        map.put("rFilePath", a.getFilePath());
                        map.put("rFileName", a.getFileName());
                    }
                }
            }
            if (drivers.size() > 0) {
                for (Attachment a : drivers) {
                    if ("head_img".equals(a.getWorkItem())) {
                        map.put("hFilePath", a.getFilePath());
                        map.put("hFileName", a.getFileName());
                        continue;
                    }
                    if ("driver_img".equals(a.getWorkItem())) {
                        map.put("dFilePath", a.getFilePath());
                        map.put("dFileName", a.getFileName());
                        continue;
                    }
                    if ("cert_img".equals(a.getWorkItem())) {
                        map.put("certFilePath", a.getFilePath());
                        map.put("certFileName", a.getFileName());
                        continue;
                    }
                    if ("work_img".equals(a.getWorkItem())) {
                        map.put("wFilePath", a.getFilePath());
                        map.put("wFileName", a.getFileName());
                    }
                }
            }
        }
        return JsonWrapper.successWrapper(map);
    }

    /**
     * 根据公司id获取公司详情.
     *
     * @param companyId 公司id
     * @return
     */
    @RequestMapping("getZtcTransportDetail")
    @ResponseBody
    public HashMap<String, Object> getZtcTransportDetail(String companyId) {
        ZtcTransport ztcTransport = ztcTransportManager.get(companyId);
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("ztcName", ztcTransport.getFullName());
        map.put("signTel", ztcTransport.getSignTel());
        map.put("address", ztcTransport.getAddress());
        map.put("time",DateFarmatUtils.format(ztcTransport.getSignTime()));
        map.put("cid", ztcTransport.getId());
        map.put("status", ztcTransport.getStatus());
        map.put("endTime",ztcTransport.getEndValidateTime()!=null?DateFarmatUtils.dateToString(ztcTransport.getEndValidateTime(),DateFarmatUtils.FORMAT_SHORT):null);
        map.put("remake", ztcTransport.getExamineRemark());
        map.put("email", ztcTransport.getEmail());
        map.put("location",sysAreaManager.findUniqueBy("code",ztcTransport.getAreaCode()).getFullName());
        map.put("type", getCompanyType(ztcTransport.getType()));
        if (ztcTransport.getType()==3||ztcTransport.getType()==5) {
            if (list.size() > 0) {
                for (Attachment a : list) {
                    if ("business_img".equals(a.getWorkItem())) {
                        map.put("busFilePath", a.getFilePath());
                        map.put("busFileName", a.getFileName());
                        continue;
                    }
                    if ("trade_img".equals(a.getWorkItem())) {
                        map.put("traFilePath", a.getFilePath());
                        map.put("traFileName", a.getFileName());
                        continue;
                    }
                    if ("oBusiness_img".equals(a.getWorkItem())) {
                        map.put("obFilePath", a.getFilePath());
                        map.put("obFileName", a.getFileName());
                        continue;
                    }
                    if ("oTrade_img".equals(a.getWorkItem())) {
                        map.put("otFilePath", a.getFilePath());
                        map.put("otFileName", a.getFileName());
                    }
                }
            }
        }
        return JsonWrapper.successWrapper(map);
    }

    /**
     * 当前session用户获取本公司详情.
     * @return
     */
    @RequestMapping("getCurrZtcTransportDetail")
    @ResponseBody
    public HashMap<String, Object> getCurrZtcTransportDetail(HttpSession session) {
         User user=(User)session.getAttribute("userInfo");
        if (user == null||user.getTransportId()==null) {
            return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试！");
        }
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("获取公司信息失败，请稍后重试！");
        }
        List<Attachment> list = attachmentManager.getAttachmentByBusinessId(user.getTransportId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("ztcName", ztcTransport.getFullName());
        map.put("signTel", ztcTransport.getSignTel());
        map.put("address", ztcTransport.getAddress());
        map.put("time",DateFarmatUtils.format(ztcTransport.getSignTime()));
        map.put("cid", ztcTransport.getId());
        map.put("status", ztcTransport.getStatus());
        map.put("remark", ztcTransport.getExamineRemark());
        map.put("endTime",ztcTransport.getEndValidateTime()!=null?DateFarmatUtils.dateToString(ztcTransport.getEndValidateTime(),DateFarmatUtils.FORMAT_SHORT):null);
        map.put("email",ztcTransport.getEmail());
        SysArea sysArea=sysAreaManager.findUniqueBy("code",ztcTransport.getAreaCode());
        map.put("location",sysArea==null?"":sysArea.getFullName());
        map.put("type", getCompanyType(ztcTransport.getType()));
        map.put("cType", ztcTransport.getType());
        if (ztcTransport.getType()==3||ztcTransport.getType()==5) {
            if (list.size() > 0) {
                for (Attachment a : list) {
                    if ("business_img".equals(a.getWorkItem())) {
                        map.put("busFilePath", a.getFilePath());
                        map.put("busFileName", a.getFileName());
                        continue;
                    }
                    if ("trade_img".equals(a.getWorkItem())) {
                        map.put("traFilePath", a.getFilePath());
                        map.put("traFileName", a.getFileName());
                        continue;
                    }
                    if ("oBusiness_img".equals(a.getWorkItem())) {
                        map.put("obFilePath", a.getFilePath());
                        map.put("obFileName", a.getFileName());
                        continue;
                    }
                    if ("oTrade_img".equals(a.getWorkItem())) {
                        map.put("otFilePath", a.getFilePath());
                        map.put("otFileName", a.getFileName());
                    }
                }
            }
        }
        return JsonWrapper.successWrapper(map);
    }

    //公司类型
    private String getCompanyType(Integer type) {
        String temp = "";
        switch (type) {
            case 0: temp = "平台公司";break;
            case 1: temp = "省级公司";break;
            case 2: temp = "地级公司";break;
            case 3: temp = "运营公司";break;
            case 4: temp = "车方公司";break;
            case 5: temp = "快递公司";break;
        }
        return temp;
    }

    /**
     * 运营公司新增.
     * @param ztcTransport  公司信息
     * @param business_img  营业执照
     * @param trade_img    行业许可证
     * @param user   注册用户信息
     * @param session
     * @param vCode    手机验证码
     * @param request
     * @return
     */
    @RequestMapping(value = "signAdd", method = RequestMethod.POST)
    @ResponseBody
    public HashMap<String,Object> signAdd(ZtcTransport ztcTransport,String business_img,String trade_img,User user,HttpSession session,String vCode,HttpServletRequest request,String endTime) {
        User currUser=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(currUser.getTransportId());
        if (ztcTransport1 == null) {
            return JsonWrapper.failureWrapperMsg("公司数据读取错误，无法操作!");
        }
        if(endTime==null||"".equals(endTime)){
            return JsonWrapper.failureWrapperMsg("证件到期时间未选择!");
        }
        ztcTransport.setBeginValidateTime(new Date());
        ztcTransport.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        if (ztcTransport.getSignTel() == null || "".equals(ztcTransport.getSignTel())) {
            return JsonWrapper.failureWrapperMsg("请输入电话号码!");
        }
        if (vCode == null || "".equals(vCode)) {
            return JsonWrapper.failureWrapperMsg("请输入验证码!");
        }
        HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
        if (map != null) {
            if (!map.get("smscode").equals(vCode)) {
                return JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!");
            }
            if (!map.get("mobile").equals(ztcTransport.getSignTel())) {
                return JsonWrapper.failureWrapperMsg("输入的手机号码异常，请重新输入!");
            }
        } else {
            return JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            return JsonWrapper.failureWrapperMsg("请设置登录密码!");
        }
        User user1 = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (user1 != null) {
            return JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!");
        }
        user.setAccount(ztcTransport.getSignTel());
        user.setTelPhone(ztcTransport.getSignTel());
        user.setStatus("1");
        String slat = StringUtils.getUUId();
        String pwd = passwordHash.toHex(user.getPassword(), slat);
        user.setSalt(slat);
        user.setPassword(pwd);
        user.setUserType("1");
        user.setCurrTime(new Date());
        user.setRemark("后台新增公司用户");
        String uid = userManager.save(user);
        if (uid == null) {
            return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!");
        }

        //系统默认提成比例方案
        List<ZtcTransportDefaultPercentage> ztcTransportDefaultPercentageList=ztcTransportDefaultPercentageManager.getAll();
        ZtcTransportDefaultPercentage ztcTransportDefaultPercentage=ztcTransportDefaultPercentageList.get(0);
        //设置分销商返佣比例及普通用户返佣比例
        ztcTransport = ZtcCompanyScaleUtil.setOperationCompany(ztcTransport, ztcTransportDefaultPercentage.getDealerUserLevelScale(), ztcTransportDefaultPercentage.getCommonUserLevelScale());
        logger.info("============设置分销商返佣比例及普通用户返佣比例==============");

        HashMap<String, Object> transportResult = ztcTransportManager.saveZtcTransport(ztcTransport, 3, 3,currUser.getTransportId());//3运营公司
        if (transportResult.get("success").equals(true)) {
            if (business_img == null || "".equals(business_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传公司营业执照，以便审核!");
            }
            if (trade_img == null || "".equals(trade_img)) {
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传行业许可证，以便审核!");
            }
            if (business_img != null) {
                Attachment attachment = new Attachment();
                attachment.setWorkItem("business_img");
                attachment.setUploadTime(new Date());
                attachment.setUploaderName("新增运营公司");
                attachment.setUploader(currUser.getId());
                attachment.setBusinessId(String.valueOf(transportResult.get("data")));
                // 通过base64来转化图片
                String[] arrays = business_img.split("\\,");
                if(arrays.length<3){
                    userManager.removeById(uid);
                    ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                    return JsonWrapper.failureWrapperMsg("证照参数错误，添加失败!");
                }
                attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
                attachment.setFileName(arrays[2]);
                attachmentManager.markImgByText(arrays[1],attachment,"An168");
                String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
                attachment.setFilePath(attachmentId);
                attachmentManager.save(attachment);
            }
            if (trade_img != null) {
                Attachment attachment = new Attachment();
                attachment.setWorkItem("trade_img");
                attachment.setUploader(currUser.getId());
                attachment.setUploadTime(new Date());
                attachment.setUploaderName("新增运营公司");
                attachment.setBusinessId(String.valueOf(transportResult.get("data")));
                // 通过base64来转化图片
                String[] arrays = trade_img.split("\\,");
                attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
                attachment.setFileName(arrays[2]);
                attachmentManager.markImgByText(arrays[1],attachment,"An168");
                String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
                attachment.setFilePath(attachmentId);
                attachmentManager.save(attachment);
            }

            //设置角色
            UserRole userRole=new UserRole();
            userRole.setRoleId("402880f25fe7b388015fe7cc729e0047");
            userRole.setUserId(uid);
            userRoleManager.save(userRole);

            //退票扣费比例
            HashMap<String,Object> resultMap=ZtcCompanyScaleUtil.setOperation(String.valueOf(transportResult.get("data")));
            ZtcRefundRatioInfo ztcRefundRatioInfo= (ZtcRefundRatioInfo)resultMap.get("ztcRefundRatioInfo");
            ztcRefundRatioInfoManager.saveInfo(ztcRefundRatioInfo,resultMap.get("ztcRefundRatio").toString());

            //设置公司提成收益比例
            ZtcTransportPercentageScale ztcTransportPercentageScale = ZtcCompanyScaleUtil.setCompanyPercentageScale(ztcTransportDefaultPercentage, ztcTransport.getType(), String.valueOf(transportResult.get("data")));
            ztcTransportPercentageScaleManager.save(ztcTransportPercentageScale);

            //初始化公司钱包
            ZtcWallet ztcWallet=new ZtcWallet();
            ztcWallet.setMoney(new BigDecimal(0));
            ztcWallet.setFkUserId(String.valueOf(transportResult.get("data")));
            ztcWallet.setBusinessType(2);
            logger.info("============公司钱包初始化==============");
            ztcWalletManager.save(ztcWallet);
            user.setTransportId(String.valueOf(transportResult.get("data")));
            userManager.update(user);
            return JsonWrapper.successWrapper("添加成功！");
        } else {
            userManager.removeById(uid);
            ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
            return JsonWrapper.failureWrapperMsg("需上传证件信息!");
        }
    }


    /**
     * 修改(运营、车方)公司资料.
     * @param ztcTransport 公司信息
     * @param business_img 营业执照
     * @param trade_img    行业许可
     * @param vCode       手机验证码
     * @param request
     * @return
     */
    @RequestMapping("updateCompany")
    @ResponseBody
    @Transactional
    public HashMap<String,Object> updateCompany(ZtcTransport ztcTransport,String business_img,String trade_img,HttpSession session,String vCode,HttpServletRequest request,String endTime) {
        User currUser=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport2 = ztcTransportManager.get(currUser.getTransportId());
        if(ztcTransport2==null){
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        //当前公司状态处于冻结状态，无法操作业务
        if (ztcTransport2.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        ZtcTransport ztcTransport1=ztcTransportManager.get(ztcTransport.getId());
        if(ztcTransport1==null){
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        if(ztcTransport1.getType()==3){
            if(endTime==null||"".equals(endTime)){
                return JsonWrapper.failureWrapperMsg("证件到期时间未选择!");
            }
            ztcTransport.setBeginValidateTime(new Date());
            ztcTransport.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
        }
        List<Attachment> list=attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
        //手机号验证
        HashMap<String, Object> x = getPhoneValidateResult(ztcTransport, session, vCode, ztcTransport1);
        if (x != null) {return x;}
        if(ztcTransport.getAreaCode()==null||"".equals(ztcTransport.getAreaCode())){
            ztcTransport.setAreaCode(ztcTransport1.getAreaCode());
        }
        ztcTransport.setType(ztcTransport1.getType());
        ztcTransport.setSignTime(ztcTransport1.getSignTime());
        ztcTransport.setParentId(ztcTransport1.getParentId());
        ztcTransport.setExamineUsername(ztcTransport1.getExamineUsername());
        ztcTransport.setExamineUserId(ztcTransport1.getExamineUserId());
        ztcTransport.setExamineRemark(ztcTransport1.getExamineRemark());
        ztcTransport.setIsPermission(ztcTransport1.getIsPermission());
        ztcTransport.setDistributorRebateProportion(ztcTransport1.getDistributorRebateProportion());
        ztcTransport.setFixedFeeDeduction(ztcTransport1.getFixedFeeDeduction());
        ztcTransport.setRevenueProportion(ztcTransport1.getRevenueProportion());
        ztcTransport.setUserRebateProportion(ztcTransport1.getUserRebateProportion());
        ztcTransport.setExamineTime(ztcTransport1.getExamineTime());
        ztcTransport.setBeginValidateTime(ztcTransport1.getBeginValidateTime());
        ztcTransport.setStatus(ztcTransport1.getStatus());
        if (business_img!=null&&business_img.contains("data")) {
            Attachment attachment = new Attachment();
            attachment.setWorkItem("business_img");
            attachment.setUploadTime(new Date());
            attachment.setUploaderName("修改营业执照");
            attachment.setUploader(currUser.getId());
            attachment.setBusinessId(ztcTransport.getId());
            // 通过base64来转化图片
            String[] arrays = business_img.split("\\,");
            if(arrays.length<3){
                return JsonWrapper.failureWrapperMsg("证照参数错误，添加失败!");
            }
            attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
            attachment.setFileName(arrays[2]);
            attachmentManager.markImgByText(arrays[1],attachment,"An168");
            if(list.size()>0){
                for (Attachment a:list) {
                    if("business_img".equals(a.getWorkItem())){
                        attachmentManager.deleteAttachment(a);
                    }
                }
            }
            String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
            attachment.setFilePath(attachmentId);
            attachmentManager.save(attachment);
        }
        if (trade_img!=null&&trade_img.contains("data")) {
            Attachment attachment = new Attachment();
            attachment.setWorkItem("trade_img");
            attachment.setUploadTime(new Date());
            attachment.setUploaderName("修改行业许可证");
            attachment.setUploader(currUser.getId());
            attachment.setBusinessId(ztcTransport.getId());
            // 通过base64来转化图片
            String[] arrays = trade_img.split("\\,");
            if(arrays.length<3){
                return JsonWrapper.failureWrapperMsg("证照参数错误，添加失败!");
            }
            attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
            attachment.setFileName(arrays[2]);
            attachmentManager.markImgByText(arrays[1],attachment,"An168");
            if(list.size()>0){
                for (Attachment a:list) {
                    if("trade_img".equals(a.getWorkItem())){
                        attachmentManager.deleteAttachment(a);
                    }
                }
            }
            String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
            attachment.setFilePath(attachmentId);
            attachmentManager.save(attachment);
        }
        ztcTransportManager.update(ztcTransport);
        return JsonWrapper.successWrapper("修改成功！");
    }

    /**
     * 车方新增
     * ( carSide_img 车身斜照
     * driver_lic_img 行驶证
     * Operation_img  运营证
     * ride_img       乘坐险
     * head_img    司机头像
     * driver_img     驾驶证
     * cert_img      资格证
     * work_img       上岗证).
     * @param ztcTransport   公司信息
     * @param vCode          手机验证码
     * @param user           车方用户信息
     * @param ztcCar         车辆信息
     * @param ztcDriver      车辆信息
     * @return 注册结果返回信息
     */
    @RequestMapping("addSignCut")
    @ResponseBody
    public HashMap<String,Object> addSignCut(ZtcTransport ztcTransport,HttpServletRequest request, String imgArrays,
                          ZtcCar ztcCar, ZtcDriver ztcDriver, String vCode, HttpSession session, User user,String endTime) {
        User currUser = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(currUser.getTransportId());
        if (ztcTransport1 == null) {
            return JsonWrapper.failureWrapperMsg("公司数据读取错误，无法操作!");
        }
        ztcTransport.setAreaCode(ztcTransport1.getAreaCode());
        if(endTime==null||"".equals(endTime)){
            return JsonWrapper.failureWrapperMsg("证件到期时间未选择!");
        }
        if(ztcTransport1.getType()!=3){
            return JsonWrapper.failureWrapperMsg("非运营公司无权限进行操作!");
        }
        //当前运营公司状态处于冻结状态，无法操作新增车方
        if (ztcTransport1.getStatus()==4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许!");
        }
        if (ztcTransport.getSignTel() == null || "".equals(ztcTransport.getSignTel())) {
            return JsonWrapper.failureWrapperMsg("请输入电话号码!");
        }
        if (vCode == null || "".equals(vCode)) {
            return JsonWrapper.failureWrapperMsg("请输入验证码!");
        }
        //手机验证码
        HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
        if (map != null) {
            if (!map.get("smscode").equals(vCode)) {
                return JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!");
            }
            if (!map.get("mobile").equals(ztcTransport.getSignTel())) {
                return JsonWrapper.failureWrapperMsg("获取验证码与该手机号码不一致，请重新输入!");
            }
        } else {
            return JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            return JsonWrapper.failureWrapperMsg("请设置登录密码!");
        }
        User user1 = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (user1 != null) {
            return JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!");
        }
        user.setAccount(ztcTransport.getSignTel());
        user.setTelPhone(ztcTransport.getSignTel());
        user.setStatus("1");
        String slat = StringUtils.getUUId();
        String pwd = passwordHash.toHex(user.getPassword(), slat);
        user.setSalt(slat);
        user.setUserType("1");
        user.setPassword(pwd);
        user.setCurrTime(new Date());
        user.setRemark("新增车方用户");
        String uid = userManager.save(user);
        if (uid == null) {
            return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!");
        }

        //设置角色
        UserRole userRole=new UserRole();
        userRole.setRoleId("402880f25fe7b388015fe7c01e140036");
        userRole.setUserId(uid);
        userRoleManager.save(userRole);

        //保存车方公司信息
        HashMap<String, Object> transportResult = ztcTransportManager.saveZtcTransport(ztcTransport, 4, 3, currUser.getTransportId());//4车方公司
        if (transportResult.get("success").equals(true)) {
            JSONObject json = JSONObject.parseObject(imgArrays);
            if(json.size()<8){
                userManager.removeById(uid);
                ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
                return JsonWrapper.failureWrapperMsg("证件资料不全，无法提交数据！");
            }
            ztcCar.setTransportId(String.valueOf(transportResult.get("data")));
            ztcCar.setStatus(1);
            ztcDriver.setTransportId(String.valueOf(transportResult.get("data")));
            ztcDriver.setBeginValidateTime(new Date());
            ztcDriver.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
            ztcDriver.setExamineUserId(currUser.getId());
            ztcDriver.setSignTime(new Date());
            ztcDriver.setExamineTime(new Date());
            ztcDriver.setStatus("1");
            String carId = ztcCarManager.save(ztcCar);
            String did = ztcDriverManager.save(ztcDriver);
            if (json.containsKey("carSide_img")) {
                attachmentManager.saveAttachment(json,"carSide_img",currUser,carId,request,"新增车方");
            }
            if (json.containsKey("driver_lic_img")) {
                attachmentManager.saveAttachment(json,"driver_lic_img",currUser,carId,request,"新增车方");
            }
            if (json.containsKey("Operation_img")) {
                attachmentManager.saveAttachment(json,"Operation_img",currUser,carId,request,"新增车方");
            }
            if (json.containsKey("ride_img")) {
                attachmentManager.saveAttachment(json,"ride_img",currUser,carId,request,"新增车方");
            }
            if (json.containsKey("head_img")) {
                attachmentManager.saveAttachment(json,"head_img",currUser,did,request,"新增车方");
            }
            if (json.containsKey("driver_img")) {
                attachmentManager.saveAttachment(json,"driver_img",currUser,did,request,"新增车方");
            }
            if (json.containsKey("cert_img")) {
                attachmentManager.saveAttachment(json,"cert_img",currUser,did,request,"新增车方");
            }
            if (json.containsKey("work_img")) {
                attachmentManager.saveAttachment(json,"work_img",currUser,did,request,"新增车方");
            }

            //系统默认提成比例方案
            List<ZtcTransportDefaultPercentage> ztcTransportDefaultPercentageList=ztcTransportDefaultPercentageManager.getAll();
            ZtcTransportDefaultPercentage ztcTransportDefaultPercentage=ztcTransportDefaultPercentageList.get(0);
            //设置公司提成收益比例
            ZtcTransportPercentageScale ztcTransportPercentageScale = ZtcCompanyScaleUtil.setCompanyPercentageScale(ztcTransportDefaultPercentage, ztcTransport.getType(), String.valueOf(transportResult.get("data")));
            ztcTransportPercentageScaleManager.save(ztcTransportPercentageScale);

            //初始化公司钱包
            ZtcWallet ztcWallet=new ZtcWallet();
            ztcWallet.setMoney(new BigDecimal(0));
            ztcWallet.setFkUserId(String.valueOf(transportResult.get("data")));
            ztcWallet.setBusinessType(2);
            logger.info("============公司钱包初始化==============");
            ztcWalletManager.save(ztcWallet);
            user.setTransportId(String.valueOf(transportResult.get("data")));
            userManager.update(user);
            return JsonWrapper.successWrapper("添加成功！");
        } else {
            userManager.removeById(uid);
            ztcTransportManager.delZtcTransport(String.valueOf(transportResult.get("data")));
            return JsonWrapper.failureWrapperMsg(String.valueOf(transportResult.get("msg")));
        }
    }

    /**
     * 获取所有省公司和地级公司.
     * @param pageSize  每页大小
     * @param pageNumber  页码
     * @return   所有满足条件的公司信息
     */
    @RequestMapping("getAreaCompany")
    @ResponseBody
    public HashMap<String, Object> getAreaCompany(@RequestParam(defaultValue ="10") Integer pageSize,@RequestParam(defaultValue ="1") Integer pageNumber,String search) {
        return ztcTransportManager.getAreaCompany(pageSize,pageNumber,search);
    }

    /**
     * 当前公司修改自己公司资料.
     * @param ztcTransport 公司信息
     * @param business_img 营业执照
     * @param trade_img    行业许可
     * @param vCode       手机验证码
     * @param request
     * @return
     */
    @RequestMapping("updateCurrCompanyInfo")
    @ResponseBody
    @Transactional
    public HashMap<String, Object> updateCurrCompanyInfo(ZtcTransport ztcTransport, String business_img, String trade_img, HttpSession session, String vCode, HttpServletRequest request) {
        User currUser = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1 = ztcTransportManager.get(ztcTransport.getId());
        if (ztcTransport1 == null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        if (!ztcTransport.getId().equals(currUser.getTransportId())) {
            return JsonWrapper.failureWrapperMsg("当前操作用户不属于该公司，无法修改！");
        }
        if (ztcTransport1.getStatus() == 4) {
            return JsonWrapper.failureWrapperMsg("公司处于冻结状态，该操作不被允许！");
        }
        //手机号验证
        HashMap<String, Object> x = getPhoneValidateResult(ztcTransport, session, vCode, ztcTransport1);
        if (x != null) {return x;}
        if (ztcTransport.getAreaCode() == null || "".equals(ztcTransport.getAreaCode())) {
            ztcTransport.setAreaCode(ztcTransport1.getAreaCode());
        }
        ztcTransport.setType(ztcTransport1.getType());
        ztcTransport.setSignTime(ztcTransport1.getSignTime());
        ztcTransport.setParentId(ztcTransport1.getParentId());
        ztcTransport.setExamineUsername(ztcTransport1.getExamineUsername());
        ztcTransport.setExamineUserId(ztcTransport1.getExamineUserId());
        ztcTransport.setExamineRemark(ztcTransport1.getExamineRemark());
        ztcTransport.setIsPermission(ztcTransport1.getIsPermission());
        ztcTransport.setDistributorRebateProportion(ztcTransport1.getDistributorRebateProportion());
        ztcTransport.setFixedFeeDeduction(ztcTransport1.getFixedFeeDeduction());
        ztcTransport.setRevenueProportion(ztcTransport1.getRevenueProportion());
        ztcTransport.setUserRebateProportion(ztcTransport1.getUserRebateProportion());
        ztcTransport.setExamineTime(ztcTransport1.getExamineTime());
        ztcTransport.setBeginValidateTime(ztcTransport1.getBeginValidateTime());
        ztcTransport.setEndValidateTime(ztcTransport1.getEndValidateTime());
        ztcTransport.setStatus(ztcTransport1.getStatus());
        //运营需要照片处理
        if (ztcTransport1.getType() == 3||ztcTransport1.getType() == 5) {
            List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
            if (business_img != null && business_img.contains("data")) {
                ztcTransport.setStatus(5);
                Attachment attachment = new Attachment();
                attachment.setWorkItem("business_img");
                attachment.setUploadTime(new Date());
                attachment.setUploaderName("修改营业执照");
                attachment.setUploader(currUser.getId());
                attachment.setBusinessId(ztcTransport.getId());
                // 通过base64来转化图片
                String[] arrays = business_img.split("\\,");
                if (arrays.length < 3) {
                    return JsonWrapper.failureWrapperMsg("证照参数错误，添加失败!");
                }
                attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
                attachment.setFileName(arrays[2]);
                attachmentManager.markImgByText(arrays[1],attachment,"An168");
                if (list.size() > 0) {
                    one:
                    for (Attachment a : list) {
                        if ("business_img".equals(a.getWorkItem())) {
                            //如果当前公司是‘正常未通过，正常待审核’，需要删除上一次提交的新照片
                            if (ztcTransport1.getStatus() == 6 || ztcTransport1.getStatus() == 5) {
                                boolean isExit = false;
                                //判断前一次是否修改过营业执照
                                two:
                                for (Attachment a1 : list) {
                                    //如果修改过，这次删除，否则更改原执照workItem
                                    if ("oBusiness_img".equals(a1.getWorkItem())) {
                                        attachmentManager.deleteAttachment(a);
                                        isExit = true;
                                        break two;
                                    }
                                }
                                if (!isExit) {
                                    a.setWorkItem("oBusiness_img");
                                    attachmentManager.update(a);
                                }
                            } else {
                                a.setWorkItem("oBusiness_img");
                                attachmentManager.update(a);
                            }
                            break one;
                        }
                    }
                }
                String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
                attachment.setFilePath(attachmentId);
                attachmentManager.save(attachment);
            }
            if (trade_img != null && trade_img.contains("data")) {
                ztcTransport.setStatus(5);
                Attachment attachment = new Attachment();
                attachment.setWorkItem("trade_img");
                attachment.setUploadTime(new Date());
                attachment.setUploaderName("修改行业许可证");
                attachment.setUploader(currUser.getId());
                attachment.setBusinessId(ztcTransport.getId());
                // 通过base64来转化图片
                String[] arrays = trade_img.split("\\,");
                if (arrays.length < 3) {
                    return JsonWrapper.failureWrapperMsg("证照参数错误，添加失败!");
                }
                attachment.setFileType(arrays[0].split(":")[1].split(";")[0]);
                attachment.setFileName(arrays[2]);
                attachmentManager.markImgByText(arrays[1],attachment,"An168");
                if (list.size() > 0) {
                    one:
                    for (Attachment a : list) {
                        if ("trade_img".equals(a.getWorkItem())) {
                            //如果当前公司是‘正常未通过，正常待审核’，需要删除上一次提交的新照片
                            if (ztcTransport1.getStatus() == 6 || ztcTransport1.getStatus() == 5) {
                                boolean isExit = false;
                                //判断前一次是否修改过营业执照
                                two:
                                for (Attachment a1 : list) {
                                    //如果修改过，这次删除，否则更改原执照workItem
                                    if ("oTrade_img".equals(a1.getWorkItem())) {
                                        attachmentManager.deleteAttachment(a);
                                        isExit = true;
                                        break two;
                                    }
                                }
                                if (!isExit) {
                                    a.setWorkItem("oTrade_img");
                                    attachmentManager.update(a);
                                }
                            } else {
                                a.setWorkItem("oTrade_img");
                                attachmentManager.update(a);
                            }
                            break one;
                        }
                    }
                }
                String attachmentId = attachmentManager.saveAttachment(attachment, request, true);
                attachment.setFilePath(attachmentId);
                attachmentManager.save(attachment);
            }
        }
        ztcTransportManager.update(ztcTransport);
        return JsonWrapper.successWrapper("提交成功！");
    }

    //修改公司资料手机号验证
    private HashMap<String, Object> getPhoneValidateResult(ZtcTransport ztcTransport, HttpSession session, String vCode, ZtcTransport ztcTransport1) {
        if (!ztcTransport.getSignTel().equals(ztcTransport1.getSignTel())) {
            if (ztcTransport.getSignTel() == null || "".equals(ztcTransport.getSignTel())) {
                return JsonWrapper.failureWrapperMsg("请输入电话号码!");
            }
            if (vCode == null || "".equals(vCode)) {
                return JsonWrapper.failureWrapperMsg("请输入验证码!");
            }
            HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
            if (map != null) {
                if (!map.get("smscode").equals(vCode)) {
                    return JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!");
                }
                if (!map.get("mobile").equals(ztcTransport.getSignTel())) {
                    return JsonWrapper.failureWrapperMsg("手机号码异常，请重新输入!");
                }
            } else {
                return JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!");
            }
            User user1 = userManager.findUniqueBy("account", ztcTransport.getSignTel());
            if (user1 != null) {
                return JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!");
            }
        }
        return null;
    }

    /**
     * 被冻结车方，更换申请更换上级运营公司.
     * @param session
     * @param pid   申请更换的运营公司ID
     * @param cid   申请所带车ID
     * @param did   申请所带司机ID
     * @return      申请反馈信息
     */
    @RequestMapping("applyChangeHigher")
    @ResponseBody
    @Transactional
    public HashMap<String,Object> applyChangeHigher(HttpSession session,String pid,String cid,String did
                    ,ZtcDriver ztcDriver,ZtcCar ztcCar,String imgArrays,boolean isExitDriver,boolean isExitCar,HttpServletRequest request){
        User user = (User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport = ztcTransportManager.get(user.getTransportId());
        if (ztcTransport == null) {
            return JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        if (ztcTransport.getType() != 4) {
            return JsonWrapper.failureWrapperMsg("您没有权限进行该操作！");
        }
        JSONArray jsonArray=JSON.parseArray(imgArrays);
        if (StringUtils.isBlank(pid)) {
            return JsonWrapper.failureWrapperMsg("请选择区域运营公司！");
        }
        if (isExitCar) {
            if (StringUtils.isBlank(cid)) {
                return JsonWrapper.failureWrapperMsg("请选择车辆！");
            }
            ZtcCar ztcCar1 = ztcCarManager.get(cid);
            if (ztcCar1 == null) {
                return JsonWrapper.failureWrapperMsg("车辆不存在！");
            }
            ztcCar1.setStatus(5);
            ztcCarManager.save(ztcCar1);
        } else {
            if (jsonArray.size() < 4) {
                return JsonWrapper.failureWrapperMsg("证件资料不全，无法提交数据！");
            }
            ztcCar.setStatus(5);
            ztcCar.setTransportId(user.getTransportId());
            String carId = ztcCarManager.save(ztcCar);
            for (int i = 0; i < jsonArray.size(); i++) {
                String jsonString = jsonArray.get(i).toString();
                String[] stringArrays = jsonString.split("\\,");
                if ("carSide_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "carSide_img", user, carId, request, "更换运营申请");
                    continue;
                }
                if ("driver_lic_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "driver_lic_img", user, carId, request, "更换运营申请");
                    continue;
                }
                if ("Operation_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "Operation_img", user, carId, request, "更换运营申请");
                    continue;
                }
                if ("ride_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "ride_img", user, carId, request, "更换运营申请");
                }
            }
        }
        if (isExitDriver) {
            if (StringUtils.isBlank(did)) {
                return JsonWrapper.failureWrapperMsg("请选择一位司机！");
            }
            ZtcDriver ztcDriver1 = ztcDriverManager.get(did);
            if (ztcDriver1 == null) {
                return JsonWrapper.failureWrapperMsg("司机不存在！");
            }
            ztcDriver1.setStatus("5");
            ztcDriverManager.save(ztcDriver1);
        } else {
            if (jsonArray.size() < 4) {
                return JsonWrapper.failureWrapperMsg("证件资料不全，无法提交数据！");
            }
            ztcDriver.setStatus("5");
            ztcDriver.setSignTime(new Date());
            ztcDriver.setTransportId(user.getTransportId());
            String driverId = ztcDriverManager.save(ztcDriver);
            for (int i = 0; i < jsonArray.size(); i++) {
                String jsonString = jsonArray.get(i).toString();
                String[] stringArrays = jsonString.split("\\,");
                if ("head_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "head_img", user, driverId, request, "更换运营申请");
                    continue;
                }
                if ("driver_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "driver_img", user, driverId, request, "更换运营申请");
                    continue;
                }
                if ("cert_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "cert_img", user, driverId, request, "更换运营申请");
                    continue;
                }
                if ("work_img".equalsIgnoreCase(stringArrays[2].trim())) {
                    attachmentManager.saveAttachment(jsonString, "work_img", user, driverId, request, "更换运营申请");
                }
            }
        }
        ztcTransport.setParentId(pid);
        ztcTransport.setStatus(1);
        ztcTransportManager.update(ztcTransport);
        return JsonWrapper.successWrapper("提交成功，请等待审核！");
    }

    /**
     * 更换申请更换上级运营（获取车，司机）.
     * @param session
     * @return
     */
    @RequestMapping("getChangeHigher")
    @ResponseBody
    public HashMap<String,Object> getChangeHigher(HttpSession session){
        User user=(User)session.getAttribute("userInfo");
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        if(ztcTransport==null){
            return  JsonWrapper.failureWrapperMsg("网络错误，请稍后重试！");
        }
        HashMap<String,Object> result=new HashMap<>();
        result.put("cars",ztcCarManager.findBy("transportId",ztcTransport.getId(),"status",1));
        result.put("drivers",ztcDriverManager.findBy("transportId",ztcTransport.getId(),"status","1"));
        return JsonWrapper.successWrapper(result);
    }

    /**
     * 首页获取本公司管理区域关系及运营公司数量.
     * @param session
     * @return
     */
    @RequestMapping("getAreaRelation")
    @ResponseBody
    public HashMap<String,Object> getAreaRelation(HttpSession session){
        User user=(User)session.getAttribute("userInfo");
        return JsonWrapper.successWrapper(ztcTransportAreaManager.getAreaRelationByCompanyId(user.getTransportId(),ztcTransportManager.get(user.getTransportId()).getType()));
    }


    /*******************************************************☟******************************************************
    ******************************웃*♥囍🌹*유*********快🍎递💰业📱务*********｡◕‿◕｡**********************************
    ****************************************************↕♨™*******************************************************
    ***************************************************************************************************************
    ***********************************************★°* 心想事成 *°★************************************************
    ***☛**┊.喜歡是浅浅的愛ヤo愛是贴着你的温暖.┊***** ★°∴°°☆°∴★*°☆∴元°∴*☆ *****************************************
    ****************************************** ★*°∴°°☆★∴°∴*°宵°∴*°☆ ********************************************
    ****************************************** ★°∴★☆∴°∴*快°∴*°☆∴*°☆ *******************************************
    ******************************************  ★☆∴*乐°∴°☆﹨☆*∴*°☆ ****┊.那年不停的奔跑ヤo只为途中与你的相见.┊**☚**
    ***************************************************************************************************************
    ****************************************************♨™↕*******************************************************
    ***************************************************************************************************************
    *************************************|`從過去。到未來。°☆。我一直都在。°.°.|*************************************
    ******************************************************☯*************************************2018*3***！*******
    ***************************************************************************************************************/

    /**
     *
     * 注册快递公司.
     *
     * @param ztcTransport 公司资料
     * @param vCode      手机验证码
     * @param expressImg  证件资料信息(business_img营业执照 trade_img行业许可证)
     * @param session
     * @param request
     * @param user   注册用户信息
     * @return
     */
    @RequestMapping("signExpressCompany")
    @ResponseBody
    public HashMap<String,Object> signExpressCompany(ZtcTransport ztcTransport,String vCode,String expressImg,HttpSession session,HttpServletRequest request,User user){
        if(StringUtils.isBlank(ztcTransport.getFullName())){
            return JsonWrapper.failureWrapperMsg("公司名称未填写！");
        }
        if(StringUtils.isBlank(ztcTransport.getSignTel())){
            return JsonWrapper.failureWrapperMsg("请输入电话号码！");
        }
        if(StringUtils.isBlank(vCode)){
            return JsonWrapper.failureWrapperMsg("请输入验证码信息！");
        }
        if(StringUtils.isBlank(expressImg)){
            return JsonWrapper.failureWrapperMsg("证件资料不完整！");
        }
        JSONObject jsonObject=JSON.parseObject(expressImg);
        if(jsonObject.size()<2){
            return JsonWrapper.failureWrapperMsg("证件资料不完整，无法提交！");
        }
        HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
        HashMap<String, Object> x = getStringObjectHashMap(ztcTransport.getSignTel(), vCode, map);
        if (x != null) {return x;};
        ZtcTransport test = ztcTransportManager.findUniqueBy("fullName", ztcTransport.getFullName());
        if (test != null) {
            if(test.getStatus()==2&&test.getSignTel().equals(ztcTransport.getSignTel())){//审核未通过且手机号通过验证
                List<Attachment> list=attachmentManager.getAttachmentByBusinessId(test.getId());
                if(list.size()>0){
                    for (Attachment a:list) {
                        attachmentManager.deleteAttachment(a);//删除证件
                    }
                }
                userManager.removeById(userManager.findUniqueBy("account",test.getSignTel()).getId());//删除登录用户
                ztcTransportManager.delZtcTransport(test.getId());//公司删除
            }
        }
        User isExitSign = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (isExitSign != null) {
            return JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!");
        }

        ZtcTransport ztcCompany=ztcTransportManager.findUniqueBy("type",0);
        Map result= ztcTransportManager.saveZtcTransport(ztcTransport,5,1,ztcCompany==null?"":ztcCompany.getId());
        if (result.get("success").equals(true)) {
            if (!jsonObject.containsKey("business_img")) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传公司营业执照，以便审核!");
            }
            if (!jsonObject.containsKey("trade_img")) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传行业许可证，以便审核!");
            }
            if (jsonObject.getString("business_img") != null&&!"".equals(jsonObject.getString("business_img"))) {
               attachmentManager.saveAttachment(jsonObject.getString("business_img"),"business_img",null,String.valueOf(result.get("data")),request,"营业执照");
            }
            if (jsonObject.getString("trade_img") != null&&!"".equals(jsonObject.getString("trade_img"))) {
                attachmentManager.saveAttachment(jsonObject.getString("trade_img"),"trade_img",null,String.valueOf(result.get("data")),request,"行业许可证");
            }
            user.setAccount(ztcTransport.getSignTel());
            user.setTelPhone(ztcTransport.getSignTel());
            user.setStatus("1");
            user.setUserType("1");
            String slat=StringUtils.getUUId();
            String pwd = passwordHash.toHex(user.getPassword(), slat);
            user.setSalt(slat);
            user.setPassword(pwd);
            user.setCurrTime(new Date());
            user.setRemark("快递公司注册用户");
            user.setTransportId(String.valueOf(result.get("data")));
            String uid = userManager.save(user);
            if (uid == null) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                List<Attachment> list=attachmentManager.getAttachmentByBusinessId(String.valueOf(result.get("data")));
                if(list.size()>0){
                    for (Attachment a:list) {
                        attachmentManager.deleteAttachment(a);//删除证件
                    }
                }
                return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!");
            }
            return JsonWrapper.successWrapper("注册成功，请等待审核!");
        } else {
            return JsonWrapper.failureWrapperMsg(String.valueOf(result.get("msg")));
        }
    }


    /**
     * 平台审核注册的快递公司.
     * @param zid     公司ID
     * @param status  审核状态(3通过，4不通过)，默认3
     * @param endTime 有效期止
     * @param remark  备注信息
     * @return
     */
    @RequestMapping("examineCompanyOfExpress")
    @ResponseBody
    @Transactional
    public HashMap<String,Object> examineCompanyOfExpress(String zid,@RequestParam(defaultValue = "3") Integer status,String endTime,String remark,HttpSession session){
        User user=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1=ztcTransportManager.get(user.getTransportId());
        if(ztcTransport1==null){
            return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试！");
        }
        if(StringUtils.isBlank(zid)){
            return JsonWrapper.failureWrapperMsg("公司信息不存在！");
        }
        if(status!=3&&status!=4){
            return JsonWrapper.failureWrapperMsg("状态参数指向性错误！");
        }
        ZtcTransport ztcTransport=ztcTransportManager.get(zid);
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("公司信息不存在！");
        }
        if(ztcTransport.getStatus()!=1&&ztcTransport.getStatus()!=5){
            return JsonWrapper.failureWrapperMsg("该公司已经审核过！");
        }
        if(ztcTransport1.getType()!=0){
            return JsonWrapper.failureWrapperMsg("您的权限不足，无法审核！");
        }
        if(status==3){
            if(StringUtils.isBlank(endTime)){
                return JsonWrapper.failureWrapperMsg("证件有效期时间不为空！");
            }
            ztcTransport.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
            //再次审核
            if(ztcTransport.getStatus()==5){
                List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
                if (list.size() > 0) {
                    for (Attachment a : list) {
                        if ("oBusiness_img".equals(a.getWorkItem())) {
                            //如果通过审核,需要删除原照片
                            attachmentManager.deleteAttachment(a);
                            continue;
                        }
                        if ("oTrade_img".equals(a.getWorkItem())) {
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
            }else{
                //注册用户
                User user1 = userManager.findUserByAccount(ztcTransport.getSignTel());
                //设置角色
                UserRole userRole = new UserRole();
                userRole.setRoleId("4028938161f442530161f54b53730000");
                userRole.setUserId(user1.getId());
                userRoleManager.save(userRole);
                ZtcWallet ztcWallet1 = ztcWalletManager.findUserWallet(ztcTransport.getId());
                if (ztcWallet1 == null) {
                    //初始化公司钱包
                    ZtcWallet ztcWallet = new ZtcWallet();
                    ztcWallet.setMoney(BigDecimal.ZERO);
                    ztcWallet.setTmoney(BigDecimal.ZERO);
                    ztcWallet.setFkUserId(ztcTransport.getId());
                    ztcWallet.setBusinessType(2);
                    ztcWalletManager.save(ztcWallet);
                }
            }
            ztcTransport.setStatus(3);
        }else{
            ztcTransport.setStatus(4);
        }
        ztcTransport.setBeginValidateTime(new Date());
        ztcTransport.setExamineRemark(remark);
        ztcTransport.setExamineTime(new Date());
        ztcTransport.setExamineUserId(user.getId());
        ztcTransport.setExamineUsername(user.getAccount());
        ztcTransportManager.update(ztcTransport);
        return JsonWrapper.successWrapper("操作成功！");
    }
    /**
     *
     * 注册旅游公司.
     *
     * @param ztcTransport 公司资料
     * @param vCode      手机验证码
     * @param tourismImg  证件资料信息(business_img营业执照 trade_img行业许可证)
     * @param session
     * @param request
     * @param user   注册用户信息
     * @return
     */
    @RequestMapping("signTourismCompany")
    @ResponseBody
    public HashMap<String,Object> signTourismCompany(ZtcTransport ztcTransport,String vCode,String tourismImg,HttpSession session,HttpServletRequest request,User user){
        if(StringUtils.isBlank(ztcTransport.getFullName())){
            return JsonWrapper.failureWrapperMsg("公司名称未填写！");
        }
        if(StringUtils.isBlank(ztcTransport.getSignTel())){
            return JsonWrapper.failureWrapperMsg("请输入电话号码！");
        }
        if(StringUtils.isBlank(vCode)){
            return JsonWrapper.failureWrapperMsg("请输入验证码信息！");
        }
        if(StringUtils.isBlank(tourismImg)){
            return JsonWrapper.failureWrapperMsg("证件资料不完整！");
        }
        JSONObject jsonObject=JSON.parseObject(tourismImg);
        if(jsonObject.size()<2){
            return JsonWrapper.failureWrapperMsg("证件资料不完整，无法提交！");
        }
        HashMap<String, String> map = (HashMap<String, String>) session.getAttribute("smsCode");
        HashMap<String, Object> x = getStringObjectHashMap(ztcTransport.getSignTel(), vCode, map);
        if (x != null) {return x;};
        ZtcTransport test = ztcTransportManager.findUniqueBy("fullName", ztcTransport.getFullName());
        if (test != null) {
            if(test.getStatus()==2&&test.getSignTel().equals(ztcTransport.getSignTel())){//审核未通过且手机号通过验证
                List<Attachment> list=attachmentManager.getAttachmentByBusinessId(test.getId());
                if(list.size()>0){
                    for (Attachment a:list) {
                        attachmentManager.deleteAttachment(a);//删除证件
                    }
                }
                userManager.removeById(userManager.findUniqueBy("account",test.getSignTel()).getId());//删除登录用户
                ztcTransportManager.delZtcTransport(test.getId());//公司删除
            }
        }
        User isExitSign = userManager.findUniqueBy("account", ztcTransport.getSignTel());
        if (isExitSign != null) {
            return JsonWrapper.failureWrapperMsg("该手机账户已存在,请更换注册!");
        }

        ZtcTransport ztcCompany=ztcTransportManager.findUniqueBy("type",0);
        Map result= ztcTransportManager.saveZtcTransport(ztcTransport,6,1,ztcCompany==null?"":ztcCompany.getId());
        if (result.get("success").equals(true)) {
            if (!jsonObject.containsKey("business_img")) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传公司营业执照，以便审核!");
            }
            if (!jsonObject.containsKey("trade_img")) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                return JsonWrapper.failureWrapperMsg("请上传行业许可证，以便审核!");
            }
            if (jsonObject.getString("business_img") != null&&!"".equals(jsonObject.getString("business_img"))) {
                attachmentManager.saveAttachment(jsonObject.getString("business_img"),"business_img",null,String.valueOf(result.get("data")),request,"营业执照");
            }
            if (jsonObject.getString("trade_img") != null&&!"".equals(jsonObject.getString("trade_img"))) {
                attachmentManager.saveAttachment(jsonObject.getString("trade_img"),"trade_img",null,String.valueOf(result.get("data")),request,"行业许可证");
            }
            user.setAccount(ztcTransport.getSignTel());
            user.setTelPhone(ztcTransport.getSignTel());
            user.setStatus("1");
            user.setUserType("1");
            String slat=StringUtils.getUUId();
            String pwd = passwordHash.toHex(user.getPassword(), slat);
            user.setSalt(slat);
            user.setPassword(pwd);
            user.setCurrTime(new Date());
            user.setRemark("快递公司注册用户");
            user.setTransportId(String.valueOf(result.get("data")));
            String uid = userManager.save(user);
            if (uid == null) {
                ztcTransportManager.delZtcTransport(String.valueOf(result.get("data")));
                List<Attachment> list=attachmentManager.getAttachmentByBusinessId(String.valueOf(result.get("data")));
                if(list.size()>0){
                    for (Attachment a:list) {
                        attachmentManager.deleteAttachment(a);//删除证件
                    }
                }
                return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试!");
            }
            return JsonWrapper.successWrapper("注册成功，请等待审核!");
        } else {
            return JsonWrapper.failureWrapperMsg(String.valueOf(result.get("msg")));
        }
    }


    /**
     * 平台审核注册的旅游公司
     * @param zid     公司ID
     * @param status  审核状态(3通过，4不通过)，默认3
     * @param endTime 有效期止
     * @param remark  备注信息
     * @return
     */
    @RequestMapping("examineCompanyOfTourism")
    @ResponseBody
    @Transactional
    public HashMap<String,Object> examineCompanyOfTourism(String zid,@RequestParam(defaultValue = "3") Integer status,String endTime,String remark,HttpSession session){
        User user=(User) session.getAttribute("userInfo");
        ZtcTransport ztcTransport1=ztcTransportManager.get(user.getId());
        if(ztcTransport1==null){
            return JsonWrapper.failureWrapperMsg("网络异常，请稍后重试！");
        }
        if(StringUtils.isBlank(zid)){
            return JsonWrapper.failureWrapperMsg("公司信息不存在！");
        }
        if(status!=3&&status!=4){
            return JsonWrapper.failureWrapperMsg("状态参数指向性错误！");
        }
        ZtcTransport ztcTransport=ztcTransportManager.get(zid);
        if(ztcTransport==null){
            return JsonWrapper.failureWrapperMsg("公司信息不存在！");
        }
        if(ztcTransport.getStatus()!=1&&ztcTransport.getStatus()!=5){
            return JsonWrapper.failureWrapperMsg("该公司已经审核过！");
        }
        if(ztcTransport1.getType()!=0){
            return JsonWrapper.failureWrapperMsg("您的权限不足，无法审核！");
        }
        if(status==3){
            if(StringUtils.isBlank(endTime)){
                return JsonWrapper.failureWrapperMsg("证件有效期时间不为空！");
            }
            ztcTransport.setEndValidateTime(DateFarmatUtils.stringToDate(endTime,DateFarmatUtils.FORMAT_SHORT));
            //再次审核
            if(ztcTransport.getStatus()==5){
                List<Attachment> list = attachmentManager.getAttachmentByBusinessId(ztcTransport.getId());
                if (list.size() > 0) {
                    for (Attachment a : list) {
                        if ("oBusiness_img".equals(a.getWorkItem())) {
                            //如果通过审核,需要删除原照片
                            attachmentManager.deleteAttachment(a);
                            continue;
                        }
                        if ("oTrade_img".equals(a.getWorkItem())) {
                            attachmentManager.deleteAttachment(a);
                        }
                    }
                }
            }else{
                //注册用户
                User user1 = userManager.findUserByAccount(ztcTransport.getSignTel());
                //设置角色
                UserRole userRole = new UserRole();
                userRole.setRoleId("402880f262fbf44f0162fbf637750000");
                userRole.setUserId(user1.getId());
                userRoleManager.save(userRole);
                ZtcWallet ztcWallet1 = ztcWalletManager.findUserWallet(ztcTransport.getId());
                if (ztcWallet1 == null) {
                    //初始化公司钱包
                    ZtcWallet ztcWallet = new ZtcWallet();
                    ztcWallet.setMoney(BigDecimal.ZERO);
                    ztcWallet.setTmoney(BigDecimal.ZERO);
                    ztcWallet.setFkUserId(ztcTransport.getId());
                    ztcWallet.setBusinessType(2);
                    ztcWalletManager.save(ztcWallet);
                }
            }
        }
        ztcTransport.setBeginValidateTime(new Date());
        ztcTransport.setExamineRemark(remark);
        ztcTransport.setExamineTime(new Date());
        ztcTransport.setExamineUserId(user.getId());
        ztcTransport.setExamineUsername(user.getAccount());
        ztcTransportManager.update(ztcTransport);
        return JsonWrapper.successWrapper("操作成功！");
    }
    private HashMap<String, Object> getStringObjectHashMap(String tel, String vCode, HashMap<String, String> map) {
        if (map != null) {
            if (!map.get("smscode").equals(vCode)) {
                return JsonWrapper.failureWrapperMsg("您输入的验证码错误，请核对后输入!");
            }
            if (!map.get("mobile").equals(tel)) {
                return JsonWrapper.failureWrapperMsg("输入的手机号码异常，请重新输入!");
            }
            return null;
        } else {
            return JsonWrapper.failureWrapperMsg("信息错误，请重新获取验证码!");
        }
    }

    /**
     * 根据类型获取快递公司列表.
     * @param type (1待审核，2全部数据不含待审核)
     * @param search 搜索条件
     * @return
     */
    @RequestMapping("getExpressCompanyList")
    @ResponseBody
    public HashMap<String,Object> getExpressCompanyList(@RequestParam(defaultValue = "1") Integer type,@RequestParam(defaultValue = "10") Integer pageSize,@RequestParam(defaultValue = "1") Integer pageNumber,String search){
        return ztcTransportManager.getExpressListByType(type,pageSize,pageNumber,search);
    }
}